﻿using Blazored.LocalStorage;
using Masa.BuildingBlocks.Service.Caller;
using Masa.Contrib.Service.Caller.HttpClient;
using Microsoft.Extensions.Options;
using System.Net.Http.Headers;
using System.Threading.Tasks;

namespace Bookify.Web.Services.Base
{
    public class BaseHttpService 
    {
        protected readonly IClient _client;
        protected readonly ILocalStorageService _localStorageService;
        protected readonly ServiceOptions _options;

        public BaseHttpService(IClient client, ILocalStorageService localStorageService, IOptions<ServiceOptions> options)
        {
            _client = client; ;
            _localStorageService = localStorageService;            
            _options = options.Value;

            // 设置默认 BaseAddress
            //_httpClient.BaseAddress = new Uri(_options.BaseAddress);             
            client.HttpClient.BaseAddress = new Uri(_options.BaseAddress);

            // 初始化时尝试添加 Token
            //AddBearerToken().GetAwaiter().GetResult();
        }

        protected async Task AddBearerToken()
        {
            if (await _localStorageService.ContainKeyAsync("token"))
            {
                var token = await _localStorageService.GetItemAsync<string>("token");
                if (!string.IsNullOrEmpty(token))
                {
                    _client.HttpClient.DefaultRequestHeaders.Authorization =
                        new AuthenticationHeaderValue("Bearer", token);
                }
            }
        }

        // 获取 HttpClient 实例供子类使用
        protected async Task<HttpClient> CreateClientAsync()
        {
            // 可以每次调用前重新设置 Token（避免 Token 失效）
            //AddBearerToken().GetAwaiter().GetResult();
            await AddBearerToken();
            return _client.HttpClient;
        }
    }
}
